# -*-coding:utf-8 -*-

from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from .models import Book, Publish
from rest_framework.serializers import ListSerializer


class BookListSerializer(ListSerializer):
    def update(self, instance, validated_data):
        for index, obj in enumerate(instance):
            self.child.update(obj, validated_data[index])
        return instance


class BookModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ('id', 'name', 'price', 'img', 'fn', 'author_list', 'publish_name',
                  'publish', 'authors',
                  )
        extra_kwargs = {
            'name': {
                'required': True,
                'min_length': 3,
                'error_messages': {
                    'required': 'name为必填项',
                    'min_length': 'name为不能少于3个字符'
                }
            },
            'publish': {'write_only': True},  # 200 反序列化字段
            'authors': {'write_only': True},  # 200 反序列化字段
            'img': {'read_only': True},  # 100 序列化字段
            'author_list': {'read_only': True},  # 100 序列化字段
            'publish_name': {'read_only': True}  # 100 序列化字段
        }
        list_serializer_class = BookListSerializer

    def validate_name(self, value):
        if 'g' in value.lower():
            raise serializers.ValidationError('g不能包含在name中')
        return value

    def validate(self, attrs):
        publish = attrs.get('publish')
        name = attrs.get('name')
        if Book.objects.filter(name=name, publish=publish):
            raise ValidationError('该书已存在')
        return attrs
